package com.yanqu.road.server.gameplayer.module.activity;

import com.yanqu.road.entity.activity.*;
import com.yanqu.road.entity.activity.civil.ActivityReceiveCivilRewardData;
import com.yanqu.road.entity.activity.civil.enums.ActivityCivilConditionTypeEnum;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.log.LogActivityCivilGetReward;
import com.yanqu.road.entity.log.LogZhenHuanThirdGetReward;
import com.yanqu.road.logic.bussiness.activity.ActivityCivilRewardBusiness;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.ActivityProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 获取-全民奖励模块
 */
public class ActivityCivilRewardModule extends GeneralModule {

    //activityId activityUserId conditionId
    private Map<Integer, Map<Long, Map<Integer, ActivityReceiveCivilRewardData>>> activityReceiveCivilRewardDataMap = new ConcurrentHashMap<>();

    public ActivityCivilRewardModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        List<ActivityInfo> activityList = NormalActivityMgr.getShowTimeActivityInfoList();
        for (ActivityInfo activityInfo : activityList) {
            //检查活动是否配置
            if (ActivityCivilConditionTypeEnum.checkActivityType(activityInfo.getType())) {
                Map<Long, Map<Integer, ActivityReceiveCivilRewardData>> activityUserMap = ActivityCivilRewardBusiness.getAdActivityUserData(activityInfo.getActivityId(), this.getUserId());
                activityReceiveCivilRewardDataMap.put(activityInfo.getActivityId(), activityUserMap);
            }
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return false;
    }

    @Override
    public boolean saveData() {
        for (Map.Entry<Integer, Map<Long, Map<Integer, ActivityReceiveCivilRewardData>>> entry : this.activityReceiveCivilRewardDataMap.entrySet()) {
            Map<Long, Map<Integer, ActivityReceiveCivilRewardData>> activityUserMap = entry.getValue();
            for (Map<Integer, ActivityReceiveCivilRewardData> conditionMap : activityUserMap.values()) {
                for (ActivityReceiveCivilRewardData activityReceiveCivilRewardData : conditionMap.values()) {
                    if (activityReceiveCivilRewardData.isInsertOption()) {
                        ActivityCivilRewardBusiness.addAdActivityUserData(activityReceiveCivilRewardData);
                    }
                }
            }
        }
        return true;
    }

    /**
     * 是否领取过奖励，false：未领取，true：已领取
     * @param activityId 活动ID
     * @param activityUserId 发起玩家ID
     * @param conditionId 任务ID
     * @return
     */
    public boolean checkReceiveRewardFlag(int activityId, long activityUserId, int conditionId) {
        Map<Long, Map<Integer, ActivityReceiveCivilRewardData>> activityUserMap = activityReceiveCivilRewardDataMap.get(activityId);
        if (activityUserMap != null) {
            Map<Integer, ActivityReceiveCivilRewardData> conditionMap = activityUserMap.get(activityUserId);
            if (conditionMap != null) {
                ActivityReceiveCivilRewardData activityReceiveCivilRewardData = conditionMap.get(conditionId);
                if (activityReceiveCivilRewardData != null) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取已领取的奖励condition id集合。set里的conditionId就是已领取的
     * @param activityId
     * @param activityUserId
     * @return
     */
    public Set<Integer> getReceivedCivilRewardConditions(int activityId, long activityUserId) {
        Set<Integer> result = new HashSet<>();
        Map<Long, Map<Integer, ActivityReceiveCivilRewardData>> activityUserMap = activityReceiveCivilRewardDataMap.get(activityId);
        if (activityUserMap != null) {
            Map<Integer, ActivityReceiveCivilRewardData> conditionMap = activityUserMap.get(activityUserId);
            if (conditionMap != null) {
                result = conditionMap.keySet();
            }
        }
        return result;
    }

    /**
     * 判断是否有全民奖励可领取
     * @param activityId 活动ID
     * @param conditionType 任务类型
     * @param activityUserIdMap k：唯一ID v：完成值
     * @return
     */
    public boolean checkCanReceiveCivilReward(int activityId, int conditionType, Map<Long, Long> activityUserIdMap) {
        //判断是否是合法conditionType
        if (!ActivityCivilConditionTypeEnum.checkConditionType(conditionType)) {
            return false;
        }
        //任务列表
        List<ActivityConditionInfo> conditionList = NormalActivityMgr.getActivityConditionInfoListByType(activityId, conditionType);
        for (ActivityConditionInfo conditionInfo : conditionList) {
            for (Map.Entry<Long, Long> entry : activityUserIdMap.entrySet()) {
                long activityUserId = entry.getKey();
                long completeValue = entry.getValue();
                BigInteger completeValueBig = BigInteger.valueOf(completeValue);
                //判断是否领取过
                boolean receivedFlag = this.checkReceiveRewardFlag(activityId, activityUserId, conditionInfo.getConditionId());
                //没领取过 && 完成值大于任务值
                if (!receivedFlag && completeValueBig.compareTo(conditionInfo.getParamList().get(3)) >= 0) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 领取全民奖励（一键领取）
     * @param activityId
     * @param conditionType
     * @param activityUserId
     * @param params
     * @return
     */
    public int sendGetConditionValueToCross(int activityId, int conditionType, long activityUserId, String params) {
        //判断活动是否存在
        ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(activityId);
        if (activityInfo == null) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        //判断活动是否在有效期
        if (!ActivityMgr.activityInTimeAndShowTime(activityInfo)) {
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }
        //判断conditionType是否符合
        if (!ActivityCivilConditionTypeEnum.checkConditionType(conditionType)) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        //发送跨服，获取任务完成数据
        ActivityProto.ActivityReceiveCivilRewardToCrossReqMsg.Builder reqMsg = ActivityProto.ActivityReceiveCivilRewardToCrossReqMsg.newBuilder();
        reqMsg.setActivityId(activityId);
        reqMsg.setConditionType(conditionType);
        reqMsg.setActivityUserId(activityUserId);
        reqMsg.setParams(params);
        YanQuMessage pkg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_ACTIVITY_RECEIVE_CIVIL_REWARD, reqMsg);
        GamePlayerMgr.sendPacket(player.getUserId(), pkg);
        return 0;
    }

    /**
     * 领取通用全民奖励（一键领取）
     * @param activityId
     * @param conditionType
     * @param activityUserId
     * @param value
     * @return
     */
    public synchronized String receiveCivilReward(int activityId, int conditionType, long activityUserId, long value) {
        Property property = new Property();
        //获取condition列表
        List<ActivityConditionInfo> list = NormalActivityMgr.getActivityConditionInfoListByType(activityId, conditionType);
        for (ActivityConditionInfo info : list) {
            //领取
            ActivityRewardResult activityRewardResult = this.receiveCivilRewardOnce(info, activityUserId, value);
            if (activityRewardResult.getRet() == 0) {
                Property onceReward = PropertyHelper.parseStringToProperty(activityRewardResult.getReward());
                property.addProperty(onceReward);
            }
        }
        return PropertyHelper.parsePropertyToString(property);
    }

    /**
     * 领取通用全民奖励（领取一个）
     * @param activityConditionInfo
     * @param activityUserId
     * @param value
     * @return
     */
    private ActivityRewardResult receiveCivilRewardOnce(ActivityConditionInfo activityConditionInfo, long activityUserId, long value) {
        int activityId = activityConditionInfo.getActivityId();
        int conditionId = activityConditionInfo.getConditionId();
        ActivityRewardResult result = new ActivityRewardResult();
        //判断活动是否存在
        ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(activityId);
        if (activityInfo == null) {
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }
        //判断conditionType是否符合
        if (!ActivityCivilConditionTypeEnum.checkConditionType(activityConditionInfo.getType())) {
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }
        //判断是否完成
        BigInteger bigValue = BigInteger.valueOf(value);
        if(value <= 0 || activityConditionInfo.getParamList().get(3).compareTo(bigValue) > 0){
            result.setRet(GameErrorCode.E_ACTIVITY_CONDITION_NO_COMPLETE);
            return result;
        }
        //判断是否已经领取
        boolean receiveFlag = this.checkReceiveRewardFlag(activityId, activityUserId, conditionId);
        if (receiveFlag) {
            result.setRet(GameErrorCode.E_ACTIVITY_REWARD_IS_GET);
            return result;
        }

        //记录领奖状态
        Map<Long, Map<Integer, ActivityReceiveCivilRewardData>> activityUserMap = this.activityReceiveCivilRewardDataMap.computeIfAbsent(activityId, k -> new ConcurrentHashMap<>());
        Map<Integer, ActivityReceiveCivilRewardData> conditionMap = activityUserMap.computeIfAbsent(activityUserId, k -> new ConcurrentHashMap<>());
        ActivityReceiveCivilRewardData activityReceiveCivilRewardData = new ActivityReceiveCivilRewardData();
        activityReceiveCivilRewardData.setUserId(player.getUserId());
        activityReceiveCivilRewardData.setActivityUserId(activityUserId);
        activityReceiveCivilRewardData.setActivityId(activityId);
        activityReceiveCivilRewardData.setConditionId(conditionId);
        activityReceiveCivilRewardData.setCreateTime(System.currentTimeMillis());
        activityReceiveCivilRewardData.setInsertOption();
        conditionMap.put(conditionId, activityReceiveCivilRewardData);

        //领取奖励
        player.getModule(CurrencyModule.class).addCurrency(activityConditionInfo.getReward(), eLogMoneyType.Activity, eLogMoneyType.ActivityCivilReceiveReward);

        //日志
        LogActivityCivilGetReward log = new LogActivityCivilGetReward(
                activityId,
                activityInfo.getType(),
                getUserId(),
                activityUserId,
                activityConditionInfo.getConditionId(),
                activityConditionInfo.getParamList().get(3).intValue(),
                activityConditionInfo.getRewardStr());
        AutoLogMgr.add(log);

        //返回
        result.setRet(0);
        result.setActivityId(activityId);
        result.setConditionId(conditionId);
        result.setReward(activityConditionInfo.getRewardStr());
        return result;
    }
}
